﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace DACU.VkontakteApi.Collections
{
	class VKParametrCollection: SortedList<string,string>
	{
		private string _formatedString = "";
		private bool _isChanged;

		public new void Add(string key,string value)
		{
			if (!ContainsKey(key))
			{
				base.Add(key, value);
				_isChanged = true;
			}
		}

		public new void Clear()
		{
			_isChanged = true;
			_formatedString = "";
			base.Clear();
		}

		public new void Remove(string key)
		{
			_isChanged = true;
			base.Remove(key);
		}

		public new void RemoveAt(int index)
		{
			_isChanged = true;
			base.RemoveAt(index);
		}

		public void ForEach(Action<string,string> action)
		{
			if (action == null)
				throw new ArgumentNullException("action");
			for (int i = 0; i < Keys.Count; i++)
				action(Keys[i],this[Keys[i]]);
		}

		public string ToFormatedString(bool withAmp=false)
		{
			if (!_isChanged)
				if (!String.IsNullOrWhiteSpace(_formatedString))
					return _formatedString;
			var sb = new StringBuilder();
			if (withAmp)
				ForEach((key, value) => sb.AppendFormat("&{0}={1}",key, value));
			else
				ForEach((key, value) => sb.AppendFormat("{0}={1}", key, value));
			_isChanged = false;
			return _formatedString = sb.ToString();
		}
	}
}
